<template>
  <div class="refine_taskplan">
    <!-- <router-view></router-view> -->
    <h2>计划任务</h2>
    <div class="contant">
      <div class="plan-operate">
        <div @click="showCreate" class="fl create" v-if="showCreateBtn">+新建计划任务</div>
        <el-form ref="form" label-width="80px">
          <el-input prefix-icon="el-icon-search" clearable placeholder="搜索任务" @clear="search"
                    v-model="searchOptions.keyword"
                    class="plansearch" @change="search">
            <span slot="append">搜索</span>
          </el-input>
          <el-form-item label="任务分配" class="planselect">
            <el-select v-model="searchOptions.target" clearable @change="search">
              <el-option v-for="(item,index) in searchOrgs" :key="index" :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="currentTab" type="card" @tab-click="switchTab" :page="currentPage">
        <el-tab-pane label="计划任务" name="scheduleTask">
          <el-table border stripe :data="currentData" style="width: 100%">
            <el-table-column prop="idx" label="序号" align="center" width="60">
              <template slot-scope="scope">
                <span v-if='scope.$index!=9'>{{(currentPage-1).toString()+parseInt(scope.$index+1)}}</span>
                <span v-else>{{currentPage+'0'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="计划任务" align="center"/>
            <el-table-column prop="number" label="任务量" align="center" width="100"/>
            <el-table-column prop="endtime" label="任务截止时间" align="center">
              <template slot-scope="scope">
                <span>{{$m(scope.row.endtime).format('YYYY-MM-DD HH:mm:ss')}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="numberComplete" label="任务进度" align="center">
              <template slot-scope="scope">
                <el-progress :text-inside="true" :stroke-width="18" :percentage="scope.row.superComplete"
                             status="exception"></el-progress>
                <span class="number">{{scope.row.finishNumber ? scope.row.finishNumber : 0}}个</span>
                <span class="number" v-if="scope.row.superComplete>0">+{{scope.row.superComplete}}个</span>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="创建人" align="center" width="120"/>
            <el-table-column prop="operate" label="操作" align="center" width="140">
              <template slot-scope="scope">
                <!-- <el-button size="mini" type="text" v-if="scope.row.userId==userId || $profile.isAdmin"
                           @click="handleEdit(scope.row, 'edit')">编辑
                </el-button> -->
                <el-button size="mini" type="text" @click="handleEdit(scope.row, 'view')">查看</el-button>
                <el-button size="mini" type="text" v-if="userId==scope.row.userId" @click="handleDel(scope.row.id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page.sync="currentPage"
                           layout="total,prev, pager, next, jumper" :total="totalpage1" background>
            </el-pagination>
          </div>
        </el-tab-pane>
        <el-tab-pane label="历史计划" name="historyTask">
          <el-table border stripe :data="historyData" style="width: 100%" :page="currentPage2">
            <el-table-column prop="idx" label="序号" align="center" width="60">
              <template slot-scope="scope">
                <span v-if='scope.$index!=9'>{{(currentPage2-1).toString()+parseInt(scope.$index+1)}}</span>
                <span v-else>{{currentPage2+'0'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="计划任务" align="center"/>
            <el-table-column prop="number" label="任务量" align="center" width="100"/>
            <el-table-column prop="endtime" label="任务截止时间" align="center">
              <template slot-scope="scope">
                <span>{{$m(scope.row.endtime).format('YYYY-MM-DD HH:mm:ss')}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="numberComplete" label="任务进度" align="center">
              <template slot-scope="scope">
                <el-progress :text-inside="true" :stroke-width="18" :percentage="(scope.row.finishNumber / scope.row.number) * 100"
                             status="exception"></el-progress>
                <span class="number">{{scope.row.finishNumber ? scope.row.finishNumber : 0}}个</span>
                <span class="number" v-if="scope.row.superComplete>0">+{{scope.row.superComplete}}个</span>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="创建人" align="center" width="120"/>
            <el-table-column prop="operate" label="操作" align="center" width="140">
              <template slot-scope="scope">
                <!-- <el-button size="mini" type="text" v-if="scope.row.userId==userId || $profile.isAdmin"
                           @click="handleEdit(scope.row, 'edit')">编辑
                </el-button> -->
                <el-button size="mini" type="text" @click="handleEdit(scope.row, 'view')">查看</el-button>
                <el-button size="mini" type="text" v-if="userId==scope.row.userId" @click="handleDel(scope.row.id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page.sync="currentPage2"
                           layout="total,prev, pager, next, jumper" :total="totalpage2" background>
            </el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>


    </div>

    <el-dialog title="" :visible.sync="showSubRoute" width="80%" append-to-body @close="close1">
        <span>
            <router-view @close="close" :sysUser="sysUser" :taskType="taskType"></router-view>
        </span>
    </el-dialog>
  </div>

</template>

<script>
  import * as orgService from '@/services/OrganizationService'
  import * as scheduleTaskService from '@/services/ScheduleTaskService'
  import * as sysUserService from '@/services/SysUserService'
  import plansService from '@/services/PlansService'
  import taskTypeService from '@/services/TaskTypeService'
  import moment from 'moment'

  export default {
    data: function () {
      return {
        currentTab: 'scheduleTask',
        searchOptions: {
          target: '',
          keyword: ''
        },
        showSubRoute: false,
        taskData: [],
        historyData: [],
        currentData: [],
        createNew: false,
        searchOrgs: [],
        showCreateBtn: false,
        userId: 0,
        totalpage1: 0,
        totalpage2: 0,
        currentPage: 1,
        currentPage2: 1,
        sysUser: [],
        taskType: []
      }
    },
    async created () {
      this.userId = this.$profile.id
      this.showCreateBtn = !this.$checkPermission('/schedule-task')
      orgService.findAll().then(async res => {
        await res.data.sort((a, b) => {
          if (a.businessOrg < b.businessOrg) {
            return -1
          }
          if (a.businessOrg > b.businessOrg) {
            return 1
          }
          return 0
        })
        this.searchOrgs = res.data
      })
      // let ret = await orgService.getScheduleTaskAssignOrg()
      // this.searchOrgs = ret
      // this.currentData = this.taskData
      this.getData()

      // this.getPlans()
      // this.getHistoryPlans()
    },
    mounted () {
      sysUserService.findAll().then(res => {
        this.sysUser = res.data
      })
      taskTypeService.search().then(res => {

        this.taskType = res
      })
    },
    methods: {
      search () {
        this.$set(this, 'currentPage', 1)
        this.$set(this, 'currentPage2', 1)
        this.getData()
      },
      handlerQuery () {
        let query = ''
        if(this.searchOptions.keyword){
          query += 'name.contains=' + this.searchOptions.keyword
        }
        if(this.searchOptions.target){
          if(query){
            query += '&'
          }
          query += 'planOrgId.equals=' + this.searchOptions.target
        }
        return query
      },
      getData (num = 0) {
        let str = this.handlerQuery()
        if (this.currentTab == 'scheduleTask') {
          this.getPlans(num, str)
        } else if (this.currentTab == 'historyTask') {
          this.getHistoryPlans(num, str)
        }
      },
      async getPlans (num, str = '') {
        let date = moment().format('YYYY-MM-DD HH:mm:ss')
        let query = 'createTime.greaterOrEqualThan=' + this.$m(date).toISOString() + (str ? `&${str}` : ``)
        plansService.filter(num, query).then(res => {
          if (res) {
            this.currentData = res.data
            this.totalpage1 = parseInt(res.headers['x-total-count'], 10)
          }
        })
      },
      async getHistoryPlans (num, str) {
        let date = moment().format('YYYY-MM-DD HH:mm:ss')
        let query = 'endTime.lessOrEqualThan=' + this.$m(date).toISOString() + (str ? `&${str}` : ``)
        plansService.filter(num, query).then(res => {
          // if (res) {
            this.historyData = res.data
            this.totalpage2 = parseInt(res.headers['x-total-count'], 10)
          // }
        })
      },
      submit: function () {
      },
      switchTab (tab) {
        this.getData()
        // if (this.currentTab === 'scheduleTask') {
        //   this.currentData = this.taskData
        // } else {
        //   this.currentData = this.historyData
        // }
      },
      handleSizeChange (val) {
        this.getData(val-1)
      },
      handleCurrentChange (val) {
        // this.currentpage = val
        // this.currentData.page = val + 1
        this.getData(val - 1)
      },
      deleteRow (index, rows) {
        rows.splice(index, 1)
      },
      showCreate () {
        // this.createNew = true
        this.showSubRoute = true
        this.$router.push({name: 'CreateScheduleTask', params: {searchOrgs: this.searchOrgs}})
      },
      handleEdit (data, type) {
        // this.createNew = false
        this.showSubRoute = true
        this.$router.push({name: 'CreateScheduleTask', params: {searchOrgs: this.searchOrgs, data: data, type: type}})
      },
      handleView (index, row) {
        this.createNew = false
        this.showSubRoute = true
        this.$router.push({path: '/schedule-task/create', query: {id: row.d_id, type: 'view'}})
      },
      handleDel (id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            plansService.delete(id).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.getData()
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },
      close () {
        this.getPlans()
        this.showSubRoute = false
        this.getData(1)
      },
      close1 () {
        this.showSubRoute = false
        this.$router.go(-1)
      },
      handleData (data) {
        let obj = {}
        obj.total = data.dataCount
        let ary = []
        data.data.forEach((d, idx) => {
          let user = d.createUser || {id: 0, fullname: ''}
          ary.push({
            idx: (this.currentData.page - 1) * 10 + idx + 1,
            endTime: d.endTime,
            name: d.name,
            creator: user.fullname,
            amount: d.amount,
            userId: user.id,
            complete: 0,
            progress: 0
          })
        })
        obj.data = ary
        obj.page = this.currentData.page
        return obj
      },
    }

  }
</script>

<style lang="scss">

  .refine_taskplan {
    width: 100%;
    display: inline-block;

    h2 {
      width: 100%;
      height: 50px;
      line-height: 50px;
      border-bottom: 1px solid #eeeeee;
      font-weight: normal;
      font-size: 18px;
      color: #0062cd;
      padding-left: 30px;
      box-sizing: border-box;
      padding: 0 0 0 30px;
      text-align: left;
    }

    .contant {
      margin-top: 20px;
      padding: 0px 30px;
      box-sizing: border-box;
    }

    .plan-operate {
      width: 100%;
      display: inline-block;
    }

    .planselect {
      float: right;
      margin-right: 10px;
    }

    .planselect input {
      width: 122px;
      border-radius: 4px;
      border: solid 1px #dddddd;
    }

    .el-table__body,
    .el-table__footer,
    .el-table__header {
      width: 100% !important;
    }

  }

  .refine_tpcreate {
    h2 {
      width: 100%;
      height: 50px;
      line-height: 50px;
      border-bottom: 1px solid #eeeeee;
      font-weight: normal;
      font-size: 18px;
      color: #0062cd;
      padding-left: 30px;
      box-sizing: border-box;
      padding: 0 0 0 30px;
      text-align: left;
    }

    .el-form {
      padding: 20px 50px;
    }

    .el-input__inner {
      border-radius: 0px;
    }

    .tpfr {
      float: right;
      text-align: left;
      width: 400px;
    }

    .el-dialog__headerbtn {
      top: 13px;
    }

    .line {
      text-align: center;
    }

    .margin90 {
      margin-left: 100px !important;
    }

    .margin80 {
      margin-left: 88px !important;
    }

    .blueclr {
      font-size: 14px;
      color: #0062cd;
    }

    .tips {
      color: #999;
      margin-top: -12px;
      margin-bottom: 20px;
    }

    .tips span {
      margin-right: 10px;
      font-size: 14px;
    }

    .el-col {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }

    .width300 {
      width: 300px;
    }

    .width300 .el-input {
      width: 220px;
      margin-right: 10px;
    }

    .checkgroup .el-form-item__content {
      width: 88%;
      border: 1px solid #ddd;
      padding: 10px;
      box-sizing: border-box;
    }

    .checkgroup .el-form-item {
      width: 100%;
    }

    .checkgroup .el-form-item .el-input {
      width: 60px;
      box-sizing: border-box;
      height: 24px;
      margin-left: 9px;
    }

    .checkgroup .el-form-item input {
      height: 24px;
      font-size: 12px;
      text-align: center;
      line-height: 24px;
    }

    .el-checkbox__input.is-checked + .el-checkbox__label {
      color: #333;
    }

    .el-upload--text {
      float: right;
      width: 58px;
      height: 40px;
      border: none;
      border-radius: 2px;
      margin-left: 5px;

      button {
        background-color: #0062cd;
        border-radius: 2px;
        border: none;
        padding: 0;
        width: 58px;
        height: 40px;
        text-align: center;
        margin-left: 0px !important;

      }
    }

    .el-upload__tip {
      width: 300px;
      height: 40px;
      border-radius: 2px;
      border: solid 1px #dddddd;
      float: left;
      margin-top: 0;
      padding: 0 15px;
      font-size: 14px;
      color: #b9b9b9;
      text-align: left;
    }

    .el-upload-list__item.is-success .el-upload-list__item-status-label {
      display: block;
      margin-top: 28px;
      margin-top: -5px;
    }

    .el-upload-list__item:first-child {
      margin-top: 0;
    }
  }
</style>
